import base64
import html
import json
import sys
import urllib.parse

import requests
import re


def openFileByNetWork(src:str, desc:str):
  rfile = open(src, encoding='utf-8')
  wfile = open(desc, 'a', encoding='utf-8')
  wfile.write('#EXTM3U\r')
  num = 1
  for line in rfile:
    if num <= 0:
      num += 1
      continue
    _line = line.strip()
    contents = _line.split("|")
    name = contents[0]
    url = contents[1]
    ret = requests.get(url=url)
    rawhtml = ret.text
    pattern =  re.compile('player_aaaa=(\{.+?})<')
    ctx = re.findall(pattern, rawhtml)
    res = json.loads(ctx[0])
    url_raw = base64.urlsafe_b64decode(res['url'])
    url_raw = unescape(url_raw)
    wfile.write('#EXTINF:-1,'+name+'\r'+url_raw+'\r')
    print(num, name, url_raw)
    num+=1

def unescape(string):
  string = urllib.parse.unquote(string)
  quoted = html.unescape(string).encode(sys.getfilesystemencoding()).decode('utf-8')
  #转成中文
  return re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: chr(int(m.group(1), 16)), quoted)
  
if __name__ == '__main__':
  # openFileByNetWork('../resources/qlz.txt', '../resources/qlz.m3u8')
  openFileByNetWork('../resources/mxdzt7.txt', '../resources/mxdzt7.m3u8')